"""
部署请假审批流程到 Flowable
"""
import sys
import os

# 添加父目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from server.app.utils.flowable_client import FlowableClient
from server.config.config import Config
from server.app.app import create_app
from server.app.utils.process_definition_sync import parse_bpmn_process_tasks, sync_process_task_definitions

def deploy_leave_approval_process():
    """部署请假审批流程"""
    
    print("=" * 60)
    print("部署请假审批流程到 Flowable")
    print("=" * 60)
    
    # 创建 Flowable 客户端
    client = FlowableClient(
        base_url=Config.FLOWABLE_REST_URL,
        username=Config.FLOWABLE_REST_USER,
        password=Config.FLOWABLE_REST_PASSWORD
    )
    
    # BPMN 文件路径
    bpmn_file = os.path.join(
        os.path.dirname(__file__),
        'processes',
        'leave-approval.bpmn20.xml'
    )
    
    if not os.path.exists(bpmn_file):
        print(f"❌ 错误: BPMN 文件不存在: {bpmn_file}")
        return False
    
    try:
        # 部署流程
        print(f"\n📁 BPMN 文件: {bpmn_file}")
        print(f"🔗 Flowable URL: {Config.FLOWABLE_REST_URL}")
        print(f"👤 用户: {Config.FLOWABLE_REST_USER}")
        print("\n正在部署流程...")
        
        result = client.deploy_process(
            bpmn_file_path=bpmn_file,
            deployment_name='请假加班审批流程'
        )
        
        print("\n✅ 流程部署成功!")
        print(f"   部署 ID: {result.get('id')}")
        print(f"   部署名称: {result.get('name')}")
        print(f"   部署时间: {result.get('deploymentTime')}")
        
        # 获取已部署的流程定义
        deployment_id = result.get('id')
        process_definition_id = None
        if 'id' in result:
            # 查询流程定义 ID
            definitions = client.get_process_definitions_by_deployment(deployment_id)
            if definitions:
                process_definition_id = definitions[0].get('id')
            print("\n📋 流程定义详情:")
            print("   流程定义 Key: leaveApproval")
            print("   流程名称: 请假/加班申请审批流程")
            print(f"   流程定义 ID: {process_definition_id}")

        # 解析 BPMN XML 并保存节点定义
        if deployment_id:
            try:
                with open(bpmn_file, 'r', encoding='utf-8') as fh:
                    xml_text = fh.read()
                definitions_by_key = parse_bpmn_process_tasks(xml_text)
                app = create_app()
                with app.app_context():
                    defs = client.get_process_definitions_by_deployment(deployment_id)
                    key_to_id = {d.get('key'): d.get('id') for d in defs if d.get('key') and d.get('id')}
                    saved = sync_process_task_definitions(definitions_by_key, key_to_id)
                    print(f"\n🗂 已保存流程节点定义 {saved} 条到数据库 (deployment_id={deployment_id})")
            except Exception as ex:
                print(f"⚠️  解析并保存流程节点定义失败: {ex}")
            
        print("\n" + "=" * 60)
        print("✨ 部署完成!")
        print("=" * 60)
        
        return True
        
    except Exception as e:
        print(f"\n❌ 部署失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


def verify_deployment():
    """验证流程部署"""
    
    print("\n正在验证流程部署...")
    
    # FlowableClient 未直接使用，可省略实例化
    
    try:
        # 可以通过 REST API 查询流程定义
        import requests
        from requests.auth import HTTPBasicAuth
        
        url = f"{Config.FLOWABLE_REST_URL}/service/repository/process-definitions"
        params = {'key': 'leaveApproval'}
        
        response = requests.get(
            url,
            params=params,
            auth=HTTPBasicAuth(Config.FLOWABLE_REST_USER, Config.FLOWABLE_REST_PASSWORD)
        )
        
        if response.status_code == 200:
            data = response.json()
            if data.get('data') and len(data['data']) > 0:
                process_def = data['data'][0]
                print("\n✅ 流程定义验证成功:")
                print(f"   流程 ID: {process_def.get('id')}")
                print(f"   流程 Key: {process_def.get('key')}")
                print(f"   版本: {process_def.get('version')}")
                print(f"   名称: {process_def.get('name')}")
                return True
            else:
                print("⚠️  未找到流程定义")
                return False
        else:
            print(f"⚠️  验证请求失败: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"⚠️  验证过程出错: {str(e)}")
        return False


if __name__ == '__main__':
    # 部署流程
    success = deploy_leave_approval_process()
    
    if success:
        # 验证部署
        verify_deployment()
        
        print("\n" + "=" * 60)
        print("📖 后续步骤:")
        print("=" * 60)
        print("1. 创建用户组:")
        print("   - direct_manager (直接主管)")
        print("   - hr_dept (HR部门)")
        print("")
        print("2. 启动 Python 服务器:")
        print("   cd server")
        print("   python run.py")
        print("")
        print("3. 测试流程:")
        print("   curl -X POST http://localhost:8000/api/leave/apply \\")
        print("     -H \"Content-Type: application/json\" \\")
        print("     -d '{")
        print('       "applicant_id": "EMP001",')
        print('       "apply_type": "leave",')
        print('       "leave_days": 2,')
        print('       "start_date": "2024-11-15",')
        print('       "end_date": "2024-11-16",')
        print('       "reason": "个人事假"')
        print("     }'")
        print("=" * 60)
    else:
        print("\n❌ 部署失败，请检查:")
        print("1. Flowable REST 服务是否运行 (http://localhost:8080/flowable-rest)")
        print("2. 用户名密码是否正确")
        print("3. BPMN 文件路径是否正确")
        sys.exit(1)
